package com.bdqn.t320.controller;

import com.bdqn.t320.pojo.SysUser;
import com.bdqn.t320.service.SysUserService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.annotation.Resources;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    Logger logger = Logger.getLogger(LoginController.class);

    @Resource
    SysUserService sysUserService;

    @RequestMapping("/login")
    public String login() {
        logger.info("login.................");
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(String userCode, String password, HttpSession session) {
        logger.info("doLogin.................");
        logger.info("userCode................." + userCode);
        logger.info("password................." + password);
        SysUser sysUser = sysUserService.loginBiz(userCode);
        if (sysUser == null) {
            logger.info("用户名不存在");
            //return "redirect: http://www.baidu.com";
            throw new RuntimeException("用户名不存在");
        } else if (!sysUser.getUserPassword().equals(password)) {
            logger.info("密码错误");
            throw new RuntimeException("密码错误");
        } else {
            logger.info("登录成功");
            session.setAttribute("sysUser", sysUser);
            //转发
            return "frame";
        }
    }

    @RequestMapping("/error")
    public String error() {
        logger.info("error.................");
        return "error";
    }

    @RequestMapping("/logOut")
    public String logOut(HttpSession session) {
        logger.info("logOut.................");
        session.removeAttribute("sysUser");
        //return "login";
        return "redirect: login";
    }

    @ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e, HttpServletRequest request) {
        request.setAttribute("e", e);
        return "login";
    }
}
